package com.zwj.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

@Slf4j
@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("日志过滤器执行了");
        ServerHttpRequest request = exchange.getRequest();
        log.info("原始路径: {}", request.getURI());
//        log.info("转发路径: " + exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR));
        return chain.filter(exchange.mutate().request(request).build()).then(
                Mono.defer(() -> {
                    String rewrittenPath = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR).toString();
                    log.info("转发路径：{}", rewrittenPath);
                    return Mono.empty();
                })
        );
    }

    @Override
    public int getOrder() {
        return 0; // 越小优先级越高
    }
}